<template>
  <div>
    <!-- 树形组件 -->
    <div class="my-tree">
      <el-tree ref="treeRef" node-key="id" show-checkbox check-strictly :data="list" :props="{ label: 'name' }" @node-click="handleNodeClick" />
    </div>
    <!-- 按钮 -->
    <div class="permission-btns">
      <el-button type="primary" round @click="onSubmit">确定</el-button>
      <el-button round @click="cancel">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionRequest } from '@/api/permission'
import { transformListToTree2 } from '@/utils'
import { assignPermissionRequest, getRoleDetailByIdRequest } from '@/api/setting'
export default {
  name: 'AssignPermission',
  props: {
    currentId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.getPermission()
  },
  methods: {
    async onSubmit() {
      try {
        const res = await assignPermissionRequest({
          id: this.currentId,
          permIds: this.$refs.treeRef.getCheckedKeys()
        })
        if (res.success) {
          //
          this.cancel()
        } else {
          this.$message.error('分配权限失败')
        }
      } catch (err) {
        console.log('assignPermissionRequest: ', err)
      }
    },
    cancel() {
      this.$emit('close')
    },
    async getPermission() {
      try {
        const res = await getPermissionRequest()
        if (res.success) {
          console.log('服务器的返回：', res.data)
          this.list = transformListToTree2(res.data, '0')
          console.log('转换为树形结构之后的数据：', this.list)
        } else {
          this.$message.error(res.message)
        }

        const res2 = await getRoleDetailByIdRequest(this.currentId)
        if (res2.success) {
          console.log(res2)
          this.$refs.treeRef.setCheckedKeys(res2.data?.permIds || [])
        } else {
          this.$message.error('当前用户的详情接口失败')
        }
      } catch (err) {
        console.log('getPermissionRequest: ', err)
      }
    },
    handleNodeClick() {}
  }
}
</script>
